import {drawImageWithAspectRatio} from "@/canvasCut/utils/ImgUtil";

export class CanvasCut {
  private width: number;
  private height: number;
  // 原始图片 需要放大或缩小比例
  private _modelScale: number = 1;
  private controll = {
    x:0,
    y:0,
    width: 0,
    height: 0
  }
  private _context: any;
  private _canvas: any;

  private _bgImageXYWH = {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    image: null
  }

  constructor(option, context: any, canvas: any) {
    this.width = option.width;
    this.height = option.height;
    this._context = context;
    this._canvas = canvas;
    console.log('option', option, this.controll)
  }

  /**
   * 渲染衣服背景
   * @param imgSrc
   */
  drawModalImg = async (imgSrc: string) => {
    if(this._bgImageXYWH.image) {
      //  渲染衣服
      this._context.drawImage(this._bgImageXYWH.image,
        this._bgImageXYWH.x,
        this._bgImageXYWH.y,
        this._bgImageXYWH.width ,
        this._bgImageXYWH.height)
      return
    }
    const { image, x, y, w , h} = await this.getImage(imgSrc)
    console.log('drawModalImg', image, x, y, w , h)
    this._bgImageXYWH = {
      x,
      y,
      width: w,
      height: h,
      image
    }
    //  渲染衣服
    this._context.drawImage( image,
        x,
        y,
        w ,
        h)
  }

  private getModelScale() {
    return this._modelScale;
  }
  public getCanvas() {
    return this._canvas;
  }

  public getImage(imgSrc: string) {
    return new Promise((resolve, reject) => {
      const image = this._canvas.createImage()
      image.onload = (res) => {
        // console.error('image loaded', image.width, image.height);
        const {x,y, w, h, scale} = drawImageWithAspectRatio(image, this.width - 10, this.height -10);
        // console.log('drawImage', x,y, w, h, this._context, this._canvas)
        this._modelScale = scale;
        resolve( {
            image,
            x: x + 5,
            y: y + 5,
            w ,
            h,
            scale
           }
        )
      }
      image.src = imgSrc
    })
  }

  public getControllerConfig(towardPosition) {
    console.log('getControllerConfig', towardPosition)
    const [cx, cy, cw, ch] = towardPosition.markedArea;
    const {x:bx, y: by, width: bw, height: bh }= this._bgImageXYWH;
      return {
        x:  bx + cx * this._modelScale,
        y:  by + cy *  this._modelScale,
        width: cw * this._modelScale,
        height: ch * this._modelScale,
        show: true
      }
  }
}
